use chrono::Local;
use std::time::Duration;
use tokio::fs::OpenOptions;
use tokio::io::AsyncWriteExt;
use tokio::time::interval;

use crate::tasks::AsyncTask;

pub struct FileTimeTask {
    file_path: String,
    interval_secs: u64,
}

impl FileTimeTask {
    pub fn new(file_path: impl Into<String>, interval_secs: u64) -> Self {
        Self {
            file_path: file_path.into(),
            interval_secs,
        }
    }
}

impl AsyncTask for FileTimeTask {
    fn start(
        self,
        stop_rx: tokio::sync::watch::Receiver<bool>,
    ) -> tokio::task::JoinHandle<Result<(), Box<dyn std::error::Error + Send + Sync>>> {
        tokio::spawn(async move {
            // 创建定时器，按指定间隔触发
            let mut interval = interval(Duration::from_secs(self.interval_secs));

            loop {
                // 检查是否收到停止信号
                if *stop_rx.borrow() {
                    break;
                }

                // 等待下一个间隔
                interval.tick().await;

                // 获取当前时间
                let now = Local::now();
                let time_str =
                    format!("文件写入任务测试： [{}]\n", now.format("%Y-%m-%d %H:%M:%S"));

                // 打开文件（追加模式）并写入
                let mut file = OpenOptions::new()
                    .create(true)
                    .append(true)
                    .open(&self.file_path)
                    .await?;

                file.write_all(time_str.as_bytes()).await?;
                file.flush().await?;
            }

            Ok(())
        })
    }
}
